﻿using UnityEngine;
using Unity.Entities;
using Unity.Transforms;
using Unity.Rendering;
using Unity.Mathematics;

namespace BallDemo
{
    public class BallSpawn
    {
        private static EntityManager _entityManager;
        private static EntityArchetype _entityArchetype;

        //在场景加载前，先初始化 EntityManager 和 Archetype
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        public static void BeforeSceneLoad()
        {
            _entityManager = World.Active.GetOrCreateManager<EntityManager>();
            //先把Position 、MeshInstanceRenderer、Rotation，后面需要设置
            _entityArchetype = _entityManager.CreateArchetype(typeof(Position), typeof(Rotation), typeof(MeshInstanceRenderer), typeof(BallDemoTag));
        }

        //在场景加载完之后，开始生成 指定数量的 Entity
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
        private static void AfterSceneLoad()
        {
            for (int i = 0; i < GameSetting.Instance.BallCount; i++)
            {
                Entity entity = _entityManager.CreateEntity(_entityArchetype);
                //这是范围内的随机位置
                float3 pos = new float3();
                pos.x = GameSetting.Instance.BallBound * UnityEngine.Random.value;
                pos.y = GameSetting.Instance.BallBound * UnityEngine.Random.value;
                pos.z = GameSetting.Instance.BallBound * UnityEngine.Random.value;
                _entityManager.SetComponentData(entity, new Position() { Value = pos });
                //设置材质和Mesh
                _entityManager.SetSharedComponentData(entity, new MeshInstanceRenderer() {
                    material = GameSetting.Instance.BallMaterial,
                    mesh = GameSetting.Instance.BallMesh
                });
            }
        }
    }
}
